﻿using Chat_IService;
using Chat_Model;
using Chat_Model.ViewModel;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Chat_Common;

namespace Chat_Service
{
    public class LarTalkRecordsService : BaseService<LarTalkRecords>, ILarTalkRecordsService
    {
        private ILarUsersService _larUsersService;
        public LarTalkRecordsService(ILarUsersService larUsersService)
        {
            _larUsersService = larUsersService;
        }

        /// <summary>
        /// 获取对话面板中的聊天记录接口  
        /// </summary>
        /// <param name="talk_type">消息来源（1：好友消息 2：群聊消息）</param>
        /// <param name="receiver_id">接收者ID</param>
        /// <param name="record_id">上次查询的最小记录ID</param>
        /// <returns></returns>
        public async Task<List<LarTalkRecordsDto>> GetRecordsList(int talk_type, int receiver_id, int record_id)
        {
            int uid = _larUsersService.GetUserId();
            Expression<Func<LarTalkRecords, bool>> expression = r =>
             ((r.UserId == uid && r.ReceiverId == receiver_id) || (r.ReceiverId == uid && r.UserId == receiver_id)) &&
                 r.TalkType == talk_type;
            
            var list = await Context.Queryable<LarTalkRecords>()
                  .LeftJoin<LarUsers>((r, u) => r.ReceiverId == u.Id && r.TalkType == 1)
                 // .LeftJoin<LarUsers>((r, u, u2) => r.UserId == u.Id && r.TalkType == 2)
                   .Where(expression)
                    .Select((r, u) => new LarTalkRecordsDto()
                    {
                        Id = r.Id,
                        Source = 0,
                        Msg_type = r.MsgType,
                        User_id = r.UserId,
                        Receive_id = r.ReceiverId,
                        Content = r.Content,
                        Is_revoke = r.IsRevoke,
                        Is_read=(byte)r.IsRead,
                        Nickname = u .Nickname,
                        Avatar = u .Avatar,
                        Created_at = r.CreatedAt
                    }).ToListAsync();

            if (record_id > 0)
            {
                list= list.FindAll(r => r.Id < record_id);
                //1expression = expression.And(r => r.Id < record_id);
            }
            return list.OrderByDescending(r => r.Created_at).ToList();

        }
    }
}